package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.bean.*;
import com.sk.bilibili.dto.DynamicInfo;
import com.sk.bilibili.dto.SearchInfo;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.sk.bilibili.mapper.SearchMapper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 邵康
 * @date 2021/11/23 21:07
 */
@Service
public class SearchService extends ServiceImpl<SearchMapper, Search> {

    @Autowired
    private VideoSetService videoSetService;
    @Autowired
    private ThemService themService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private LiveService liveService;

    public R<Void> add(Search search) {
        save(search);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(Search search) {
        updateById(search);
        return R.success();
    }

    public R<IPage<Search>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page, size), null));
    }

    public R<List<String>> searchTip(String keyword) {
        QueryWrapper<VideoSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", keyword);
        queryWrapper.select("title");
        List<VideoSet> list = videoSetService.list(queryWrapper);
        List<String> collect = list.stream().map(VideoSet::getTitle).collect(Collectors.toList());
        return R.success(collect);
    }

    // 在获取提示时  再判断获取数量过多再删除之前的搜索历史
    public R<List<Search>> getHistory() {
        int memberId = BSessionUtils.getMemberId();
        QueryWrapper<Search> queryWrapper = QueryWrapperUtils.eq("member_id", memberId);
        queryWrapper.orderByDesc("create_date");
        queryWrapper.last("limit 20");
        return R.success(list(queryWrapper));
    }

    public R<IPage<VideoSet>> searchVideo(SearchInfo searchInfo) {
        QueryWrapper<VideoSet> queryWrapper = new QueryWrapper<>();
        if (searchInfo.getTypeId() != null) queryWrapper.eq("type_id", searchInfo.getTypeId());
        queryWrapper.like("title", searchInfo.getKeyword());
        queryWrapper.orderByDesc(searchInfo.getVideoSetColumn());
        return R.success(videoSetService.searchVideo(searchInfo.page(), queryWrapper));
    }

    public R<IPage<Live>> searchLive(SearchInfo searchInfo) {
        QueryWrapper<Live> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", searchInfo.getKeyword());
        queryWrapper.orderByDesc(searchInfo.getLiveColumn());
        return R.success(liveService.searchLive(searchInfo.page(),queryWrapper));
    }

    public void addSearch(String keyword) {
        Search search = new Search();
        search.setContent(keyword);
        search.setMemberId(BSessionUtils.getMemberId());
        save(search);
    }

    public R<IPage<Them>> searchThem(SearchInfo searchInfo) {
        return R.success(themService.searchThem(searchInfo));
    }

    public R<IPage<Member>> searchMember(SearchInfo searchInfo) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("nick_name", searchInfo.getKeyword());
        queryWrapper.orderByDesc(searchInfo.getMemberColumn());
        return R.success(memberService.searchMember(searchInfo.page(), queryWrapper));
    }

    public R<Void> deleteAll() {
        QueryWrapper<Search> queryWrapper = QueryWrapperUtils.eq("member_id",
                BSessionUtils.getMemberId());
        remove(queryWrapper);
        return R.success();
    }

    public R<List<Search>> getRandom(Integer size) {
        return R.success(baseMapper.getRandom(size));
    }

    public R<Void> addSearchHistory(String keyword) {
        addSearch(keyword);
        return R.success();
    }

    @EventListener(condition = "event.type == 'com.sk.bilibili.service.DynamicService.pageSearch'")
    public void handleSearchPage(BiliBiliEvent<DynamicInfo> event){
        DynamicInfo dynamicInfo = event.getData();
        if(dynamicInfo.getPage()!=1)return;//只有第一次 搜索添加
        addSearch(dynamicInfo.getKeyword());
    }

    //  保留每个用户 最新的 20条记录
    public void clearSearch() {//先查找超过 20条的 再  把他们超出20条的删除
        List<Map<String,Object>> res=baseMapper.getOverMembers();
        for (Map<String,Object> map:res){//数据库 不支持 in  删除 多余的
            // 注意  默认数据库 汇总数据(产生的数据) 都是Long
            baseMapper.deleteOver((Integer) map.get("id"),(Long) map.get("num")-20);
        }
    }

}
